/*
 * Copyright 2011 David de Mingo
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.shalma.internal.reflection;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.shalma.internal.EntityInfo;
import org.shalma.internal.EntityManager;
import org.shalma.model.Entity;
import org.shalma.persistence.PersistenceException;

public class MetaEntityRegistry {

	private final Map<Class<?>, MetaEntity> classToEntityMapper;
	private final Map<byte[], MetaEntity> idToEntityMapper;

	private static MetaEntityRegistry INSTANCE = new MetaEntityRegistry();

	public static MetaEntityRegistry getInstance() {
		return INSTANCE;
	}

	private MetaEntityRegistry() {

		classToEntityMapper = new HashMap<Class<?>, MetaEntity>();
		idToEntityMapper = new HashMap<byte[], MetaEntity>();
	}

	public MetaEntity getMetaEntity(Entity entity) {

		return getEntityMapper(entity.getClass());
	}

	public MetaEntity getMetaEntity(Class entityClass) {
		return getEntityMapper(entityClass);
	}

	public MetaEntity getMetaEntity(byte[] classId) {

		MetaEntity entityMapper = idToEntityMapper.get(classId);

		if (entityMapper == null) {
			for (EntityInfo entityInfo : getEntityManager().getEntityInfos()) {

				Class<? extends Entity> entityClass = entityInfo
						.getEntityClass();
				if (Arrays.equals(classId, IdGenerator.getId(entityClass))) {
					entityMapper = getEntityMapper(entityClass);
					break;
				}
			}
		}

		if (entityMapper == null) {
			throw new PersistenceException("Register entity: "
					+ IdGenerator.encodeURL(classId));
		}

		return entityMapper;
	}

	private MetaEntity getEntityMapper(Class<? extends Entity> entityClass) {

		MetaEntity entityMapper = classToEntityMapper.get(entityClass);

		if (entityMapper == null)
			synchronized (entityClass) {
				if (entityMapper == null)

					try {
						entityMapper = new MetaEntity(entityClass);
						classToEntityMapper.put(entityClass, entityMapper);
						idToEntityMapper.put(IdGenerator.getId(entityClass),
								entityMapper);

					} catch (Exception e) {
						throw new PersistenceException(e);
					}
			}

		return entityMapper;
	}

	private EntityManager getEntityManager() {
		return null;
	}
}
